package main

import (
	//	"fmt"
	"log"
	"net/http"

	"git.oschina.net/index.php/gostudy/restful/proxy"

	"flag"

	"github.com/ant0ine/go-json-rest/rest"
)

func main() {
	// 启动参数
	os_iface := flag.String("i", "", "绑定网卡")
	os_ip := flag.String("h", "", "入口代理IP")
	os_port := flag.Int("p", 3001, "代理端口")
	os_addr := flag.String("r", "", "注册中心地址")

	flag.Parse()
	if *os_iface == "" {
		log.Fatalln("请设置绑定的网卡")
		return
	}
	if *os_ip == "" {
		log.Fatalln("请设置入口代理IP")
		return
	}

	if *os_addr == "" {
		log.Println("===> 警告：未设置注册中心地址，默认注册到:127.0.0.1:8080")
		*os_addr = "127.0.0.1:8080"
	}

	svcs := proxy.Service{
		Iface:    *os_iface,
		BindIp:   *os_ip,
		BindPort: *os_port,
		Addr:     *os_addr,
		Store:    map[string]*proxy.Proxy{},
	}

	// 注册服务发现
	if !svcs.Register() {
		return
	}

	// 同步加载所有配置
	svcs.LoadConfig("")

	// 启动代理服务
	log.Printf("===> 在网卡[%s]上启动代理服务", *os_iface)
	log.Printf("===> API: %s:%d/v1", *os_ip, *os_port)
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Get("/v1/proxy", svcs.GetAll),
		rest.Post("/v1/proxy", svcs.Create),
		rest.Get("/v1/proxy/reload", svcs.ReloadAll),
		rest.Get("/v1/proxy/reload/:id", svcs.Reload),
		rest.Get("/v1/proxy/:id", svcs.Show),
		rest.Put("/v1/proxy/:id", svcs.Update),
		rest.Delete("/v1/proxy/:id", svcs.Delete),
	)

	if err != nil {
		log.Fatal(err)
	}
	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":8081", api.MakeHandler()))
}
